﻿
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using System.Text.RegularExpressions;
using System.Text;
using WebAPI.Middleware;

namespace WebAPI.Common.Extensions
{
    public static class HttpContextExtension
    {
        /// <summary>
        /// 当前登录的用户id
        /// </summary>
        /// <returns></returns>
        public static Guid GetCurrentUserId(this HttpContext context)
        {
            Guid _userId = Guid.Empty;
            if (context.User.Identity.IsAuthenticated)
            {
                try
                {
                    var userIdStr = context.User.Claims.GetClaim("AccountId");

                    Guid.TryParse(userIdStr, out _userId);
                }
                catch
                {
                    return Guid.Empty;
                }


            }
            return _userId;
        }


        /// <summary>
        /// 当前登录的用户id
        /// </summary>
        /// <returns></returns>
        public static string GetCurrentLoginName(this HttpContext context)
        {

            string _logiName = string.Empty;
            if (context.User.Identity.IsAuthenticated)
            {
                var claimList = context.User.Claims.ToList();
                _logiName = claimList.FirstOrDefault(t => t.Type == ConstantDim.ApiLoginNameClaimType)?.Value ?? "";
            }
            return _logiName;
        }

        /// <summary>
        /// 获取客户端IP
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static string GetClientIp(this HttpContext context)
        {
            if (context == null) return "";
            var result = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
            if (string.IsNullOrEmpty(result))
            {
                result = context.Connection.RemoteIpAddress?.ToString();
            }
            if (string.IsNullOrEmpty(result) || result.Contains("::1"))
                result = "127.0.0.1";

            result = result.Replace("::ffff:", "127.0.0.1");

            //Ip规则效验
            var regResult = Regex.IsMatch(result, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");

            result = regResult ? result : "127.0.0.1";
            return result;
        }

        public static string GetSessionID(this HttpContext context)
        {
            //TODO：get session id from request header
            return Guid.NewGuid().ToString(); //test
        }

        public static string GetTokenStr(this HttpContext context)
        {
            //TODO：get token string from request header
            return Guid.NewGuid().ToString(); //test
        }

        public static string GetAccountId(this HttpContext context)
        {
            //TODO：get token string from request header
            return context.GetCurrentUserId().ToString();//test
        }

        public static string GetPlatformLoginName(this HttpContext context)
        {
            //TODO：get token string from request header
            return context.GetCurrentLoginName().ToString();//test
        }

        /// <summary>
        /// 获取浏览器标识
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static string GetUserAgent(this HttpContext context)
        {
            return context.Request.Headers["User-Agent"];
        }

        /// <summary>
        /// 获取请求Body参数
        /// </summary>
        /// <param name="context"></param>
        /// <param name="reqMethod"></param>
        /// <returns></returns>
        public static string GetRequestValue(this HttpContext context, string reqMethod)
        {
            string param;

            if (HttpMethods.IsPost(reqMethod) || HttpMethods.IsPut(reqMethod))
            {
                context.Request.Body.Seek(0, SeekOrigin.Begin);
                using var reader = new StreamReader(context.Request.Body, Encoding.UTF8);
                //需要使用异步方式才能获取
                param = reader.ReadToEndAsync().Result;
            }
            else
            {
                param = context.Request.QueryString.Value is null ? "" : context.Request.QueryString.Value.ToString();
            }
            return param;
        }


    }
}
